<?php
function debug($data)
{
    global $log;
    if(is_array($data))
    {
        $data = var_export($data,true);
    }
    $log->write_error_log($data);
}
/**
 * 序列化的字符串转化为数组
 *
 * @param unknown_type $str
 * @return unknown
 */
function str_to_array($str)
{
    return unserialize($str);
}
/**
 * 将数组序列化
 *
 * @param unknown_type $array
 * @return unknown
 */
function array_to_str($array)
{
    return serialize($array);
}


function new_addslashes($string)
{
	$conf = array(
		array('\\\'','\\"','\\\\'),
		array('\'','"','\\')
	);
	if(!is_array($string))
	{ 
		return str_replace($conf[0],$conf[1],$string);
	}
	foreach($string as $key => $val) $string[$key] = new_addslashes($val);
	return $string;
}

/**
 * 格式化路径
 *
 * @param 模块名 $module
 * @param 文件名 $file
 * @param 参数 $params
 * @return string
 */
function format_url($url)
{
	return $url;
}

/**
 * 模板编译
 * @para string $file 模板文件(如：discuz, forumdata, viewthread等)
 * @para int $templateid 用的是哪套模板中的，若没有的话用TEMPLATEID这个常数取代
 * @para string $tpldir 模板所在的目录
 * @return string 解析好的模板文件，通过include template('xxx')这样引用到文件，framework的MVC也是这样一个模式的
 */
function template($dir, $filename)
{
	if(defined('MODULE_TEMPLATE_PATH'))
	{
		$compiledhtmlfile = MODULE_TEMPLATE_PATH."$dir/$filename.html";
		if(!file_exists($compiledhtmlfile))
		{
			$compiledhtmlfile = TEMPLATE_PATH."$dir/$filename.html";
			$compiledtplfile = TEMPLATE_CACHE_PATH."$dir/$filename.tpl.php";
		}
		else 
		{
			$compiledtplfile = TEMPLATE_CACHE_PATH."module/".MODULE_NAME."/$dir/$filename.tpl.php";
		}
		
	}
	else 
	{
    	$compiledhtmlfile = TEMPLATE_PATH."$dir/$filename.html";
    	$compiledtplfile = TEMPLATE_CACHE_PATH."$dir/$filename.tpl.php";
	}
    
    if(!file_exists($compiledtplfile) || filemtime($compiledhtmlfile) > @filemtime($compiledtplfile))
    {
		include_once 'template.class.php';
		parse_template($dir, $filename, $compiledhtmlfile, $compiledtplfile);
	}
	return $compiledtplfile;
}

/**
 * 客户端ip
 *
 * @return string
 */
function ip()
{
	if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown'))
	{
		$ip = getenv('HTTP_CLIENT_IP');
	}
	elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown'))
	{
		$ip = getenv('HTTP_X_FORWARDED_FOR');
	}
	elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown'))
	{
		$ip = getenv('REMOTE_ADDR');
	}
	elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown'))
	{
		$ip = $_SERVER['REMOTE_ADDR'];
	}
	return preg_match("/[\d\.]{7,15}/", $ip, $matches) ? $matches[0] : 'unknown';
}


/**
 * 文字标题缩略显示
 * @author zham, 20080105
 *
 * @param string $string
 * @param integer $limit
 * @param string $ext_str
 * @return string
 */
function str_cut($string, $limit=10, $ext_str="..."){
	$string = trim($string);
	if(get_real_len($string, "UTF-8") > $limit){
		return get_real_sub($string, $limit, "UTF-8").$ext_str;
	}else{
		return $string;
	}
}

/**
 * 获得字符串的真实长度
 * @author zham, 20080105
 *
 * @param string $str
 * @param string $charset
 * @return integer
 */
function get_real_len($str, $charset="UTF-8") {
	if (!$str) return 0;
	$len = 0;
	$cnt = mb_strlen($str, $charset);
	for ($i = 0; $i < $cnt; $i++) {
		$char = mb_substr($str, $i, 1, $charset);
		if (ord($char) < 128) {
			$len += 1;
		} else {
			$len += 2;
		}
	}
	return $len;
}

/**
 * 获得截取指定长度的子字符串
 * @author zham, 20080105
 *
 * @param string $str
 * @param integer $limit
 * @param string $charset
 * @return string
 */
function get_real_sub($str, $limit, $charset="UTF-8") {
	if (!$str) return 0;
	$sub = "";
	$len = 0; $i = 0;
	do {
		$char = mb_substr($str, $i, 1, $charset);
		$sub .= $char;
		if (ord($char) < 128) {
			$len += 1;
		} else {
			$len += 2;
		}
		$i++;
	} while ($len < $limit);
	return $sub;
}

function get($sql, $rows = 0, $page = 0, $show_type = FRONT_PAGE_TYPE)
{
    global $db;
	if(!$sql) return false;
	$rows = intval($rows);
	if(!isset($page)) $page = 1;
	$page = max(intval($page), 0);
	$pages = $limit = '';
	if($page)
	{
		$offset = $rows*($page-1);
		$limit = " LIMIT $offset, $rows";
		$total = cache_count("SELECT COUNT(*) AS `count` ".stristr($sql, 'from'));
		$pages = pages($total, $page, $rows, $show_type);
	}
	elseif($rows > 0)
	{
		$limit = " LIMIT $rows";
	}
    $data = $rows == -1 ? $db->query($sql) : $db->query($sql.$limit);
	if($page)
	{
		$count = count($data);
		if(!isset($total)) $total = $count;
		return array('data'=>$data, 'total'=>$total, 'count'=>count($data), 'pagecount'=>ceil($total/$rows), 'pages'=>$pages);
	}
	else
	{
		return $data;
	}
}
/**
 * 根据catid获取内容表数据
 * @author menghao
 * @param $catid 所属栏目
 * @param $thumb 0所有1只获取带图片的
 * @param $rows 返回记录数
 * @param $page 第几页
 * @param $show_type 分页类型
 */
function get_content($catid, $thumb = 0, $rows = 0, $page = 0, $show_type = FRONT_PAGE_TYPE)
{
    global $db, $site_id;
	if(!$catid) return false;

    $sql = "select c.*,r.cid from ".DB_PRE."content c,".DB_PRE."content_rel r  where r.catid='$catid'
    and c.id = r.contentid and siteid='$site_id' and c.status=".STATUS_NORMAL;
    if($thumb)
    {
        $sql .= " and c.thumb <> ''";
    }
    $sql .= " order by c.listorder desc, c.addtime desc";
	$rows = intval($rows);
	if(!isset($page)) $page = 1;
	$page = max(intval($page), 0);
    return get($sql, $rows, $page, $show_type);
}

function cache_count($sql)
{
	global $db;
	$result = $db->query($sql);
    if(is_array($result))
    {
        foreach($result as $r)
        {
            if(isset($r['count'])) $count = $r['count'];
        }
    }
	return $count;
}

function ads($id,$width=0,$height=0)
{
	global $db;
	$info = $db->get_one_normal(DB_PRE.'advertisement', $id, 'adsid');
	if(!isset($info['adsid']))
	{
		echo '此广告不存在';
	}
	switch ($info['adstype'])
	{
		case 'image':
			$img_string = '<img src="'.UPLOAD_URL.$info['adscontent'].'" width="'.$width.'" height="'.$height.'" border=0>';
			echo empty($info['linkurl']) ? $img_string : '<a href="'.$info['linkurl'].'" target="_blank">'.$img_string.'</a>';
			break;
		case 'flash':
			$flash_string = '<object classid=\'clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\' codebase=\'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,19,0\' width=\''.$width.'\' height=\''.$height.'\'>	<param name=\'movie\' value=\''.UPLOAD_URL.$info['adscontent'].'\' /><param name=\'quality\' value=\'high\' />	<param name=\'wmode\' value=\'opaque\' />	<embed src=\''.UPLOAD_URL.$info['adscontent'].'\' width=\''.$width.'\' height=\''.$height.'\' quality=\'high\' wmode=\'opaque\' pluginspage=\'http://www.macromedia.com/go/getflashplayer\' type=\'application/x-shockwave-flash\'></embed></object>';
			echo empty($info['linkurl']) ? $flash_string : '<a href="'.$info['linkurl'].'" target="_blank">'.$flash_string.'</a>';
			break;
		case 'link':
			echo empty($info['linkurl']) ? $info['adscontent'] : '<a href="'.$info['linkurl'].'" target="_blank">'.$info['adscontent'].'</a>';
			break;
		case 'text':
		default:
			echo $info['adscontent'];
	}
}

function pages($total, $page = 1, $perpage = 20, $show_type=3)
{
	if($total < 1) return '';
	$pages = ceil($total/$perpage);
//	$page = min($pages, $page);
	$prepage = $page - 1;
	$prepage = max($prepage, 1);
	$nextpage = $page+1;
	$nextpage = min($nextpage, $pages);
	include_once 'page.class.php';
    $page = new page(array('total'=>$total,'perpage'=>$perpage,'nowindex'=>$page));
    $url=$page->show($show_type);
	return $url;
}

function muti_pages($total,$count,$page = 1)
{
    $total = $total > 0 ? $total : 1;
    $needle= strrpos($_SERVER['REQUEST_URI'], '/')+1;
    $url=substr($_SERVER['REQUEST_URI'], 0, $needle);
    $page_arr = array();
    $first = 1;
    $last = $total;
    $page_str = '<div align="center">共有'.$count.'条记录  |  当前页'.$page.'/'.$total.' |  <a href="'.$url.'1.html">首页</a> | ';
    $pre = $page > 1 ? ($page - 1) : 1;
    $next = $page < $total ? ($page + 1) : $total;
    if($page >1)
    {
        $page_str .= '<a href="'.$url.$pre.'.html">上一页</a> | ';
    }
    if($page < $last)
    {
        $page_str .= '<a href="'.$url.$next.'.html">下一页</a> | ';
    }
    $page_str .= '<a href="'.$url.$last.'.html">尾页</a> | 转到第  <select name="select" onChange="javascript:tiao(this.value,\''.$url.'\')" >';
    for($i=1;$i<=$last;$i++)
    {
        if($i==$page)
        {
            $page_str .= '<option value="'.$i.'"  selected>'.$i.'</option>';
        }
        else
        {
            $page_str .= '<option value="'.$i.'">'.$i.'</option>';
        }
    }
    $page_str .= '</select> 页</div>';
    return $page_str;
}

function muti_pages_active($total,$page = 1)
{
    if($total == 1 )
    {
        return '';
    }
          //自动获取
    if(empty($_SERVER['QUERY_STRING'])){
           //不存在QUERY_STRING时
        $url=$_SERVER['REQUEST_URI']."?page=";
    }
    else
    {
        if(stristr($_SERVER['QUERY_STRING'],'page=')){
            //地址存在页面参数
         $url=str_replace('page='.$page,'',$_SERVER['REQUEST_URI']);
         $last=$url[strlen($url)-1];
         if($last=='?'||$last=='&'){
             $url.="page=";
         }else{
             $url.='&page=';
         }
        }else{
            //
         $url=$_SERVER['REQUEST_URI'].'&page=';
        }//end if
       }//end if
    
    $page_arr = array();
    $step = 5;
    $first = $page - $step;
    $first = $first > 0 ? $first : 1;
    $last = $page + $step;
    $last = $last > $total ? $total : $last;
    $page_str = '';
    $pre = $page > 1 ? ($page - 1) : 1;
    $page_str .= '<a href="'.$url.$pre.'" class="prev">上一页</a>'; 
    $page_str .= '<div class="num">';
    if($first > 2)
    {
        $page_str .= '<a href="'.$url.'1">1</a><span class="pass">...</span>';
    }
    for($i=$first;$i<=$last;$i++)
    {
        if($i==$page)
        {
            $page_str .= '<a href="'.$url.$i.'" class="cur">'.$i.'</a>';
        }
        else
        {
            $page_str .= '<a href="'.$url.$i.'">'.$i.'</a>';
        }
    }
    if($last < ($total - 1))
    {
         $page_str .= '<span class="pass">...</span><a href="'.$url.$total.'">1</a>';
    }
    $page_str .= '</div>';
    $next = $page < $total ? ($page + 1) : $total;
    $page_str .= '<a href="'.$url.$next.'" class="next">下一页</a>';
    return $page_str;
}

function pages_review($total, $maxpage, $page = 1,$show_type=FRONT_PAGE_TYPE,$perpage=5)
{
    if($total < 1) return '';
    $pages = $maxpage;
    $page = min($pages, $page);
    $prepage = $page-1;
    $prepage = max($prepage, 1);
    $nextpage = $page+1;
    $nextpage = min($maxpage, $nextpage);
    $url = '';
    $url .="<div id='pages'>title:<b>$total</b>";
    if($pages == 1)
     {
        $url .= "<span class=''>first</span>"."<span class=''>prev</span>next last</a>pages<b><font color='red'>$page</font>/$pages</b>";
     }
     else
     {
         if($page == 1)
         {
            $url .="<span class=''>first</span><span class=''>prev</span><a href='history.php?page=$nextpage'>next</a><a href='history.php?page=$pages'>last</a>pages<b><font color='red'>$page</font>/$pages</b>";
         }
         elseif($page == $pages)
         {
            $url .="<a href='history.php?page=1'>first</a><a href='history.php?page=$prepage'>prev</a><span class=''>next</span><span class=''>last</span>pages<b><font color='red'>$page</font>/$pages</b>";
         }
         else
         {
             $url .="<a href='history.php?page=1'>first</a><a href='history.php?page=$prepage'>prev</a><a href='history.php?page=$nextpage'>next</a><a href='history.php?page=$pages'>last</a>pages<b><font color='red'>$page</font>/$pages</b>";
         }
     }
       $url .="</div>";

    return $url;

}

function input($key)
{
    if(isset($_REQUEST[$key])) return $_REQUEST[$key];
}

function url($url, $isabs = 0)
{
	if(strpos($url, '://') !== FALSE || $url[0] == '?') return $url;
	if($isabs || defined('SHOWJS'))
	{
		$url = strpos($url, APP_PATH) === 0 ? SITE_URL.substr($url, strlen(APP_PATH)) : SITE_URL.$url;
	}
	else
	{
		$url = strpos($url, APP_PATH) === 0 ? $url : APP_PATH.$url;
	}
	return $url;
}

function new_htmlspecialchars($string)
{
	return is_array($string) ? array_map('new_htmlspecialchars', $string) : htmlspecialchars($string, ENT_QUOTES);
}


function new_stripslashes($string)
{
	if(!is_array($string)) return stripslashes($string);
	foreach($string as $key => $val) $string[$key] = new_stripslashes($val);
	return $string;
}

function text2html($string,$cutlen=false)
{
	if(intval($cutlen) > 0)
	{
		$string = str_cut($string, $cutlen);
	}
	return nl2br(str_replace(' ','&nbsp;',new_htmlspecialchars($string)));
}

function filter_xss($string, $allowedtags = '', $disabledattributes = array('onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 'onbeforecopy', 'onbeforecut', 'onbeforedeactivate', 'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange', 'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut', 'ondataavaible', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick', 'ondeactivate', 'ondrag', 'ondragdrop', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate', 'onfilterupdate', 'onfinish', 'onfocus', 'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete', 'onload', 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmoveout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange', 'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 'onresizestart', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll', 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop', 'onsubmit', 'onunload'))
{
	if(is_array($string))
	{
		foreach($string as $key => $val) $string[$key] = filter_xss($val, ALLOWED_HTMLTAGS);
	}
	else
	{
		$string = preg_replace('/\s('.implode('|', $disabledattributes).').*?([\s\>])/', '\\2', preg_replace('/<(.*?)>/ie', "'<'.preg_replace(array('/javascript:[^\"\']*/i', '/(".implode('|', $disabledattributes).")[ \\t\\n]*=[ \\t\\n]*[\"\'][^\"\']*[\"\']/i', '/\s+/'), array('', '', ' '), stripslashes('\\1')) . '>'", strip_tags($string, $allowedtags)));
	}
	return $string;
}

function safe_replace($string)
{
	$string = str_replace('%20','',$string);
	$string = str_replace('%27','',$string);
	$string = str_replace('*','',$string);
	$string = str_replace('"','&quot;',$string);
	$string = str_replace("'",'',$string);
	$string = str_replace("\"",'',$string);
	$string = str_replace('//','',$string);
	$string = str_replace(';','',$string);
	$string = str_replace('<','&lt;',$string);
	$string = str_replace('>','&gt;',$string);
	$string = str_replace('(','',$string);
	$string = str_replace(')','',$string);
	$string = str_replace("{",'',$string);
	$string = str_replace('}','',$string);
	return $string;
}

function thumb($imgurl, $width = 100, $height = 100 ,$autocut = 1, $smallpic = 'nopic.gif')
{
	global $image;
    $smallpic = empty($smallpic) ? $smallpic : IMAGE_URL.'nopic.gif';
	if(empty($imgurl)) return $smallpic;
	if(!extension_loaded('gd') || strpos($imgurl, '://')) return $imgurl;
	if(!file_exists(APP_ROOT.$imgurl)) return $smallpic;
	list($width_t, $height_t, $type, $attr) = getimagesize(APP_ROOT.$imgurl);
	if($width>=$width_t || $height>=$height_t) return $imgurl;
	$newimgurl = dirname($imgurl).'/thumb_'.$width.'_'.$height.'_'.basename($imgurl);
	if(file_exists(APP_ROOT.$newimgurl)) return $newimgurl;
	if(!is_object($image))
	{
		require_once 'image.class.php';
		$image = new image();
	}
	return $image->thumb(APP_ROOT.$imgurl, APP_ROOT.$newimgurl, $width, $height, '', $autocut) ? $newimgurl : $imgurl;
}

function date_tool($name, $value = '', $isdatetime = 0)
{
	if($value == '0000-00-00 00:00:00') $value = '';
	$id = preg_match("/\[(.*)\]/", $name, $m) ? $m[1] : $name;
	if($isdatetime)
	{
		$size = 21;
		$format = '%Y-%m-%d %H:%M:%S';
		$showsTime = 'true';
	}
	else
	{
		$size = 10;
		$format = '%Y-%m-%d';
		$showsTime = 'false';
	}
	$str = '';
	$str .= '<input type="text" name="'.$name.'" id="'.$id.'" value="'.$value.'" size="'.$size.'">&nbsp;';
	$str .= '<script language="javascript" type="text/javascript">
				date = new Date();document.getElementById ("'.$id.'").value="'.$value.'";
				Calendar.setup({
					inputField     :    "'.$id.'",
					ifFormat       :    "'.$format.'",
					showsTime      :    '.$showsTime.',
					timeFormat     :    "24"
				});
			</script>';
	return $str;
}

function forward_encode($url)
{
	return urlencode(base64_encode($url));
}

function forward_decode($url)
{
	return base64_decode(urldecode($url));
}
/**
 * 生成当前页面的后退地址参数
 *
 * @return unknown
 */
function make_forward($url='')
{
	$url = !empty($url) ? $url : $_SERVER['REQUEST_URI'];
	return forward_encode($url);
}

/**
 * 获得后退地址参数
 *
 * @param unknown_type $default_url
 * @return unknown
 */
function get_forward($default_url='')
{
	$forward = isset($_GET['forward']) ? $_GET['forward'] : (isset($_POST['forward']) ? $_POST['forward']:'');
	$forward = isset($forward) ? forward_decode($forward) : '';
	$forward = empty($forward) ? $default_url : $forward;
	return $forward;
}

function showmessage($message, $forward='')
{
    include template('admin', 'showmessage');
    exit;
}

/**
 * 写缓存
 * @author menghao
 * @param <string> $key
 * @param <mixed> $value
 * @return <boolean>
 */
function cache_write($key, $value, $cache_path=false)
{
    include_once 'cache/cache.class.php';
    $c = new CacheEngine;
    $conf = array('cachetype'=>'file','dir'=>$cache_path==false ? CACHE_PATH : $cache_path);
    $c->get_instance($conf);

    return $c->set($key, serialize($value));
}

/**
 * 读缓存
 * @author menghao
 * @param <string> $key
 * @return <mixed>
 */
function cache_read($key)
{
    include_once 'cache/cache.class.php';
    $c = new CacheEngine;
    $conf = array('cachetype'=>'file','dir'=>CACHE_PATH);
    $c->get_instance($conf);

    return unserialize($c->get($key));
}

/**
 * 删缓存
 * @author wangxz
 * @param <string> $file, $path
 * @return <boolean>
 */
function cache_delete( $file, $path = '' )
{
	$cachefile = ( $path ? $path : CACHE_PATH ) . $file;
	return @unlink( $cachefile );
}

/**
 * 获取缓存对象
 *
 * @return object
 */
function get_cache_obj()
{
	include_once 'cache/cache.class.php';
    $c = new CacheEngine;
    $conf = array('cachetype'=>'file','dir'=>CACHE_PATH);
    $obj = $c->get_instance($conf);
    return $obj;
}

function cache_all_category()
{
    global $db, $site_conf;
    //如果当前站点是主站，更新所有缓存到本站缓存
    $db->prepare('select * from '.DB_PRE.'category where status=?');
    $db->set_int(STATUS_NORMAL);
    $category = $db->execute();
    $category_list = array();
    if(is_array($category))
    {
        foreach ($category as $c)
        {
            $category_list[$c['catid']] = $c;
        }
    }
    cache_write('CACHE_ALL_CATEGORY',$category_list);
}

if(!function_exists('file_put_contents'))
{
	define('FILE_APPEND', 8);
	function file_put_contents($file, $data, $append = '')
	{
		$mode = $append == '' ? 'wb' : 'ab';
		$fp = @fopen($file, $mode) or exit("Can not open file $file !");
		flock($fp, LOCK_EX);
		$len = @fwrite($fp, $data);
		flock($fp, LOCK_UN);
		@fclose($fp);
		return $len;
	}
}

function createhtml($file)
{
	$data = ob_get_contents();
	ob_clean();
	dir_create(dirname($file));
	$strlen = file_put_contents($file, $data);
	@chmod($file,0777);
	return $strlen;
}

function fieldsclean($content) {
	$content = trim($content);
	$content = str_replace("|","&#124;",$content);
	return $content;
}

/**
 * 接收从$_POST传送的参数并进行处理
 * @return array
 */
function my_post($data='') {
	$data = $data? $data: $_POST;
	$post = array();
	foreach($data as $key => $vtmp) {
		if(is_array($vtmp))
		{
			$post[$key] = my_post($vtmp);
		} else {
			$post[$key] = fieldsclean($vtmp);
		}
	}
	return $post;
}

/**
 * 接收从$_GET传送的参数并进行处理
 * @return array
 */
function my_get($data='') {
	$data = $data? $data: $_GET;
	$get = array();
	foreach($data as $key => $vtmp) {
		if(is_array($vtmp))
		{
			$get[$key] = my_post($vtmp);
		} else {
			$get[$key] = fieldsclean($vtmp);
		}
	}
	return $get;
}

//获取详细页伪静态地址
function make_show_url( $id )
{
    if( isset( $id ) && !empty( $id ) )
    {
        $url = $id.'.html';
    }
    else
    {
        $url =  "javascript:void(0);";
    }
    return $url;
}

//获取列表页伪静态地址
function make_list_url( $path )
{
    return ( isset( $path ) && !empty( $path ) ) ? $path : "javascript:void(0);";
}

function url_par($par, $url = '')
{
	if($url == '') $url = URL;
	$pos = strpos($url, '?');
	if($pos === false)
	{
		$url .= '?'.$par;
	}
	else
	{
		$querystring = substr(strstr($url, '?'), 1);
		parse_str($par, $pars);
		foreach($pars as $k=>$v)
		{
			$querystring = _url_par($k, $v, $querystring);
		}
		$url = substr($url, 0, $pos).'?'.$querystring;
	}
	return $url;
}

function _url_par($var, $value, $querystring)
{
	if($querystring)
	{
		$pattern = "/([&]?)(".preg_quote($var)."\=)([^&]+)([&]?)/";
		$querystring = preg_match($pattern, $querystring) ? preg_replace($pattern, '${1}${2}'.$value.'${4}', $querystring) : $querystring."&$var=$value";
	}
	else
	{
		$querystring = $var.'='.$value;
	}
	return $querystring;
}

function implodeids($array, $s = ',')
{
	if(empty($array)) return '';
	return is_array($array) ? implode($s, $array) : $array;
}

/**
 * 获得当前子站id
 *
 * @return string
 */
function get_current_site()
{
	global $site_conf;
	$conf = $site_conf->get_site_conf();
	if(array_key_exists('IS_MASTER', $conf) && $conf['IS_MASTER'] == 1)
	{
		$siteid = isset($_GET['site_id']) ? $_GET['site_id'] : (isset($_POST['site_id']) ? $_POST['site_id'] : 'master');
	}
	else 
	{
		$siteid = isset($conf['SITE_ID']) ? $conf['SITE_ID'] : 'master';
	}
        return empty($siteid) ? 'master' : $siteid;
}

/**
 * 发出404错误信息
 */
function raise404()
{
    header("HTTP/1.0 404 Not Found");
    exit;
}

function get_moudule_info()
{
	$modules = array();
	if (is_dir(APP_ROOT)) 
	{
	    if ($dh = opendir(APP_ROOT)) 
	    {
	        while (($file = readdir($dh)) !== false) 
	        {
	            if($file != '.' && $file != '..' && is_dir(APP_ROOT.$file))
	            {
	            	if ($tdh = opendir(APP_ROOT.$file)) 
	            	{
	            		while (($_file = readdir($tdh)) !== false) 
	            		{
	            			if(substr($_file,-9) == '.conf.php')
	            			{
	            				$tmp = require APP_ROOT.$file.'/'.$_file;
	            				$modules[$tmp['name']] = $tmp;
	            			}
	            		}
	            		closedir($tdh);
	            	}
	            }
	        }
	        closedir($dh);
	    }
	}
	return $modules;
}


/**
 * 简单数组合并，为了纠正array_merge函数的bug 如冲突保留arr1的数据
 * @author menghao
 * @param <array> $arr1
 * @param <array> $arr2
 * @return <array>
 */
function array_merge_simple($arr1, $arr2)
{
    if(!is_array($arr1) || !is_array($arr2))
    {
    	return false;//参数只能是数组
    }
    foreach($arr2 as $i=>$r)
    {
        if(!isset($arr1[$i])) //键不存在
        {
            $arr1[$i] = $r;
        }
        else  //键存在
        {
            if(is_array($r) && is_array($arr1[$i])) //如果键相同并且值都为数组，则合并值
            {
                $arr1[$i] = array_merge_simple($arr1[$i], $r);
            }
            else
            {
                $arr1[] = $r;
            }
        }
    }
    return $arr1;
}


/**
 * 判断一个值是否在另一个数组中
 * @author menghao
 * @param <mixed> $needle
 * @param <array> $haystack
 * @return <type>
 */
function in_array_simple($needle, $haystack)
{
    if(!is_array($haystack))
    {
        throw new Exception('$haystack must be an array!');
    }
    if(empty($haystack))
    {
        return false;
    }
    foreach($haystack as $value)
    {
        if($value == $needle)
        {
            return true;
        }
        if(is_array($value) && in_array_simple($needle, $value))
        {
            return true;
        }
    }
    return false;
}

/**
 * 判断$value是否为空，如果是则返回默认值，否则返回本来值
 * @author menghao
 * @param <mixed> $value 本来值
 * @param <mixed> $default 默认值
 * @return <mixed>
 */
function get_null($value, $default = '')
{
    return isset($value) ? $value : $default;
}

/**
 * 获取所有站点列表
 * @author:menghao
 * @param : none
 * @return : 站点列表数组 key为站点标识，value为站点名称
 *
 */
function site_list()
{
    global $db;
    $table_name = DB_PRE.'sites';
    $db->prepare("select * from $table_name where status=? order by lasttime asc ");
    $db->set_int(STATUS_NORMAL);
    $data = $db->execute();

    $site_list = array();
    foreach($data as $r)
    {
        $site_list[$r['id']] = $r['sitename'];
    }
    return $site_list;
}

/**
 * 根据站点id获取站点根目录
 * @global <type> $site_conf
 * @param <string> $siteid 站点id 默认为当前站点id
 * @param <int> $fullpath 0返回相对路径1返回绝对路径
 * @return <string>
 */
function site_root($siteid = '', $fullpath = 0)
{
    global $site_conf;
    $current_siteid = $site_conf->get('SITE_ID');
    $siteid = empty($siteid) ? $current_siteid : $siteid;

    if($current_siteid != MASTER_ID) //在子站运行
    {
        $relpath = '';
    }
    else if($siteid == MASTER_ID) //
    {
        $relpath = '';
    }
    else //在主站运行切目标为子站
    {
        $relpath = SITE_PATH . $siteid .'/';
    }

    return $fullpath ? APP_ROOT . $relpath  : $relpath;
}

/**

 * 根据站点id获取站点配置信息
 * @param <string> $siteid 站点id
 * @return <array>
 */
function site_config($siteid)
{
    $site_root = site_root($siteid, 1);
    return new siteconf($site_root . 'site.conf');
}

/**
 * 根据站点id获取站点url
 * @param <string> $siteid 站点id 默认为当前站点id
 * @return <string>
 */
function site_url($siteid = '')
{
    $site_config = site_config($siteid);
    return $site_config->get('SITE_URL');
}

/**
 * 将数组格式化为jsonp格式
 * @author menghao
 * @param $data<array>要格式化的数据
 * @param $callback<string>jsonp回调函数
 * reutrn<string>格式化后的字符串
 */
function out_to_jsonp($data, $callback)
{
    $json = json_encode($data);
    echo "$callback($json)";
    exit;
}

function check_email($email)
{
	if (!preg_match("/^[0-9a-zA-Z_-]+(\.[0-9a-zA-Z_-]+)*@[a-zA-Z0-9_-]+(\.{1}[a-zA-Z0-9_-]+)*\.{1}[a-zA-Z]{2,4}$/i",$email))
  	{
        return false;
  	}
  	return  true;
}
	
function convertip($ip) {
    $dat_path = APP_ROOT.'/qqwry.Dat';
    if(!$fd = @fopen($dat_path, 'rb')){
        return 'IP date file not exists or access denied';
    }
    $ip = explode('.', $ip);
    $ipNum = $ip[0] * 16777216 + $ip[1] * 65536 + $ip[2] * 256 + $ip[3];
    $DataBegin = fread($fd, 4);
    $DataEnd = fread($fd, 4);
    $ipbegin = implode('', unpack('L', $DataBegin));
    if($ipbegin < 0) $ipbegin += pow(2, 32);
    $ipend = implode('', unpack('L', $DataEnd));
    if($ipend < 0) $ipend += pow(2, 32);
    $ipAllNum = ($ipend - $ipbegin) / 7 + 1;
    $BeginNum = 0;
    $EndNum = $ipAllNum;
    while($ip1num>$ipNum || $ip2num<$ipNum) {
        $Middle= intval(($EndNum + $BeginNum) / 2);
        fseek($fd, $ipbegin + 7 * $Middle);
        $ipData1 = fread($fd, 4);
        if(strlen($ipData1) < 4) {
            fclose($fd);
            return 'System Error';
        }
        $ip1num = implode('', unpack('L', $ipData1));
        if($ip1num < 0) $ip1num += pow(2, 32);
        if($ip1num > $ipNum) {
            $EndNum = $Middle;
            continue;
        }
        $DataSeek = fread($fd, 3);
        if(strlen($DataSeek) < 3) {
            fclose($fd);
            return 'System Error';
        }
        $DataSeek = implode('', unpack('L', $DataSeek.chr(0)));
        fseek($fd, $DataSeek);
        $ipData2 = fread($fd, 4);
        if(strlen($ipData2) < 4) {
            fclose($fd);
            return 'System Error';
        }
        $ip2num = implode('', unpack('L', $ipData2));
        if($ip2num < 0) $ip2num += pow(2, 32);
        if($ip2num < $ipNum) {
            if($Middle == $BeginNum) {
                fclose($fd);
                return 'Unknown';
            }
            $BeginNum = $Middle;
        }
    }
    $ipFlag = fread($fd, 1);
    if($ipFlag == chr(1)) {
        $ipSeek = fread($fd, 3);
        if(strlen($ipSeek) < 3) {
            fclose($fd);
            return 'System Error';
        }
        $ipSeek = implode('', unpack('L', $ipSeek.chr(0)));
        fseek($fd, $ipSeek);
        $ipFlag = fread($fd, 1);
    }
    if($ipFlag == chr(2)) {
        $AddrSeek = fread($fd, 3);
        if(strlen($AddrSeek) < 3) {
            fclose($fd);
            return 'System Error';
        }
        $ipFlag = fread($fd, 1);
        if($ipFlag == chr(2)) {
            $AddrSeek2 = fread($fd, 3);
            if(strlen($AddrSeek2) < 3) {
                fclose($fd);
                return 'System Error';
            }
            $AddrSeek2 = implode('', unpack('L', $AddrSeek2.chr(0)));
            fseek($fd, $AddrSeek2);
        } else {
            fseek($fd, -1, SEEK_CUR);
        }
        while(($char = fread($fd, 1)) != chr(0))
        $ipAddr2 .= $char;
        $AddrSeek = implode('', unpack('L', $AddrSeek.chr(0)));
        fseek($fd, $AddrSeek);
        while(($char = fread($fd, 1)) != chr(0))
        $ipAddr1 .= $char;
    } else {
        fseek($fd, -1, SEEK_CUR);
        while(($char = fread($fd, 1)) != chr(0))
        $ipAddr1 .= $char;

        $ipFlag = fread($fd, 1);
        if($ipFlag == chr(2)) {
            $AddrSeek2 = fread($fd, 3);
            if(strlen($AddrSeek2) < 3) {
                fclose($fd);
                return 'System Error';
            }
            $AddrSeek2 = implode('', unpack('L', $AddrSeek2.chr(0)));
            fseek($fd, $AddrSeek2);
        } else {
            fseek($fd, -1, SEEK_CUR);
        }
        while(($char = fread($fd, 1)) != chr(0)){
            $ipAddr2 .= $char;
        }
    }
    fclose($fd);
    if(preg_match('/http/i', $ipAddr2)) {
        $ipAddr2 = '';
    }
    $ipaddr = "$ipAddr1 $ipAddr2";
    $ipaddr = preg_replace('/CZ88.Net/is', '', $ipaddr);
    $ipaddr = preg_replace('/^s*/is', '', $ipaddr);
    $ipaddr = preg_replace('/s*$/is', '', $ipaddr);
    if(preg_match('/http/i', $ipaddr) || $ipaddr == '') {
        $ipaddr = 'Unknown';
    }
    $ipaddr = iconv('gbk', 'utf-8//IGNORE', $ipaddr); 
    if( $ipaddr != '  ' )
        return $ipaddr;
    else
        $ipaddr = 'Unknown';
        return $ipaddr;
} 

function get_current_area_by_ip($ip)
{
    $addr = convertip($ip);
    $tmp = explode('|_sss_|', str_replace(array('省','市'), '|_sss_|', $addr));
    if(is_array($tmp) && sizeof($tmp) >= 2)
    {
        return $tmp[1];
    }
    else
    {
        return $addr;
    }
}


function getCSVdata($filename)  
{  
    $row = 1;//第一行开始   
    if(($handle = fopen($filename, "r")) !== false)   
    {  
        while(($dataSrc = fgetcsv($handle)) !== false)   
        {  
            $num = count($dataSrc);  
            for ($c=0; $c < $num; $c++)//列 column    
            {  
                if($row === 1)//第一行作为字段    
                {  
                    $dataName[] = $dataSrc[$c];//字段名称   
                }  
                else  
                {  
                    foreach ($dataName as $k=>$v)  
                    {  
                        if($k == $c)//对应的字段   
                        {  
                            $data[$v] = $dataSrc[$c];  
                        }  
                    }  
                }  
            }  
            if(!empty($data))  
            {  
                 $dataRtn[] = $data;  
                 unset($data);  
            }  
            $row++;  
        }  
        fclose($handle);  
        return $dataRtn;  
    }  
}  

?>
